package com.ys.peony.services;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;

import com.example.websocket.WsManager;
import com.example.websocket.listener.WsStatusListener;
import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.ui.activity.MessageActivity;
import com.ys.peony.utils.LogUtil;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.ToastUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Response;
import okio.ByteString;

/**
 * describe:websocket通知模块服务
 * author:yukang
 * date:2017/9/11
 */

public class ServerPushService extends Service {

    private final static String TAG = "00000";
    private String ws_url = HttpURL.WEBSOCKET_URL + SharePreferencesUtils.getInstance().getUserId();
    private WsManager wsManager;

    private WsStatusListener wsStatusListener = new WsStatusListener() {
        @Override
        public void onOpen(Response response) {
            LogUtil.d(TAG, "onOpen" + " url:" + ws_url + " session:" + SharePreferencesUtils.getInstance().getSessionId()
                    + " thread-->" + Thread.currentThread().getName());
        }

        @Override
        public void onMessage(String text) {
            LogUtil.d(TAG, "onMessage-->" + text + " Thread-->" + Thread.currentThread().getName());
            initNotification(text);
            ToastUtils.showToast(text);
        }

        @Override
        public void onMessage(ByteString bytes) {
            LogUtil.d(TAG, "onMessage_bytes");
        }

        @Override
        public void onReconnect() {
            LogUtil.d(TAG, "onReconnect");
        }

        @Override
        public void onClosing(int code, String reason) {
            LogUtil.d(TAG, "onClosing");
        }

        @Override
        public void onClosed(int code, String reason) {
            LogUtil.d(TAG, "onClosed");
        }

        @Override
        public void onFailure(Throwable t, Response response) {
            LogUtil.d(TAG, "onFailure");
        }
    };
    private LocalBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        public ServerPushService getService() {
            return ServerPushService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        if (wsManager != null) {
            wsManager.stopConnect();
            wsManager = null;
        }
        wsManager = new WsManager.Builder(getBaseContext())
                .client(
                        new OkHttpClient().newBuilder()
                                .pingInterval(15, TimeUnit.SECONDS)
                                .retryOnConnectionFailure(true)
                                .build())
                .needReconnect(false)
                .wsUrl(ws_url)
                .build();
        wsManager.setWsStatusListener(wsStatusListener);
        wsManager.startConnect();
        LogUtil.e(ws_url);
        return mBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        if (wsManager != null) {
            wsManager.stopConnect();
            wsManager = null;
        }
        return super.onUnbind(intent);
    }

    /**
     * 描述：初始化系统消息通知栏
     */
    private void initNotification(final String message) {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setContentText(message) //设置内容
                .setSmallIcon(R.mipmap.app_logo) //设置icon（必须设置,不然会导致通知显示不出来）
                .setPriority(Notification.PRIORITY_DEFAULT) //设置优先级
                .setWhen(System.currentTimeMillis()) //设置时间
                .setVibrate(new long[]{0, 300, 500, 700}) //设置震动
                .setDefaults(Notification.DEFAULT_SOUND); //设置显示时间
        Intent intent = new Intent(this, MessageActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);
        Notification notify = builder.build();
        notify.flags = Notification.FLAG_NO_CLEAR;
        manager.notify(1, notify);
    }
}
